package org.snail.proxy.client;

import org.snail.proxy.client.config.ProxyConfig;
import org.snail.proxy.proto.Client;
import org.snail.proxy.proto.MessageId;
import org.snail.proxy.proto.NetType;
import org.snail.proxy.proto.Packet;
import org.snail.proxy.proto.ProxyRequest;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class InitRunner implements ApplicationRunner {
	private final ProxyConfig proxyConfig;

	public InitRunner(ProxyConfig proxyConfig) {
		this.proxyConfig = proxyConfig;
	}

	/**
     * 在服务启动完成（特指SpringApplication）后立即执行
     */
    @Override
    @Async
    public void run(ApplicationArguments args) {
        initServer();
    }
    
	/**
	 * 初始化TCP服务
	 */
	private void initServer() {
		proxyConfig.getGroup().forEach(agentConfig -> {
			Client client = new ProxyClient(agentConfig);
			client.connect(proxyConfig.getIp(), proxyConfig.getPort());
			ProxyRequest request = ProxyRequest.newBuilder().setProxyPort(agentConfig.getProxyPort()).setToken("").setType(NetType.valueOf(agentConfig.getType().toUpperCase())).build();
			client.sendMessage(new Packet((byte) 0, MessageId.PROXY_REQUEST_VALUE, request.toByteArray()));
		});
	}
}
